import router from '../router/index.ts'
import { buildMenuTree } from '../utils/dynamicRouter'

let isAdded = false

router.beforeEach(async (to, from, next) => {
  const token = localStorage.getItem('code_user')

  if (token) {
    if (!isAdded) {
      const raw = localStorage.getItem('menuRoutes')
      if (raw) {
        const menuList = JSON.parse(raw)
        const asyncRoutes = buildMenuTree(menuList)
        asyncRoutes.forEach(route => router.addRoute(route))
        isAdded = true
        next({ ...to, replace: true })
        return
      }
    }
    next()
  } else {
    if (to.path === '/login') next()
    else next('/login')
  }
})
